const express = require("express");
const multer = require("multer");
const logger = require("./logger");
const getPublicIP = require("./ip");

const app = express();

const storage = multer.diskStorage({
    destination(req, file, cb) {
        cb(null, "./temp");
    },
    filename(req, file, cb) {
        cb(null, Buffer.from(file.originalname, "latin1").toString("utf8"));
    },
});

const upload = multer({ storage });

app.use(express.json());

app.post("/uploadFile", upload.single('source'), async (req, res) => {
    const { cookie } = req.headers;
    if (!cookie) {
        res.status(401).send(
            JSON.stringify({
                data: null,
                codeMsg: "未授权：必须上传文件",
                code: "9999",
                success: false,
            })
        );
    }
    logger.info("cookie: %s", cookie);

    const file = req.file;
    if (!file) {
        res.status(400).send(
            JSON.stringify({
                data: null,
                codeMsg: "参数错误：必须上传文件",
                code: "9999",
                success: false,
            })
        );
        return;
    }
    logger.info("upload file: %j", file);

    res.end(JSON.stringify({
        data: {
            url: `/download?fileId=${file.filename}`,
        },
        codeMsg: "上传成功",
        code: "200",
        success: true,
    }));
})

app.get("/download", async (req, res) => {
    const { filename, } = req.query;
    const { cookie } = req.headers;
    logger.info("cookie: %s", cookie);
    res.download(`./temp/${filename}`);
})

app.listen(3000, () => {
    logger.info("Server started on host: %s, port: %s", getPublicIP(), 3000);
});
